package testProject;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.onpositive.page.pagerendering.AccountsManagementRenderer;
import com.onpositive.page.pagerendering.EditLinkRenderer;
import com.onpositive.storage.managers.AccountManager;

public class AuthorizationCheckFilter implements Filter {

	public void destroy() {
		
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		if (!AccountManager.isUserLoginned()) {
			HttpServletRequest req = (HttpServletRequest) arg0;
			HttpServletResponse resp = (HttpServletResponse) arg1;
			String reqStr = req.getRequestURI();
			
			String s = req.getHeader("Referer");
			if (s == null
					|| s.indexOf(AccountsManagementRenderer.LOGIN_SUFFIX) == -1) {							
				reqStr ="/index.page";//+= AccountsManagementRenderer.LOGIN_SUFFIX;
				resp.sendRedirect(reqStr);
			}else{				
				if( reqStr.indexOf(EditLinkRenderer.SUFFIX) != -1 ){
					reqStr = reqStr.replaceAll(EditLinkRenderer.SUFFIX,"");
				}else{
					reqStr = "/index.page";
				}
				resp.sendRedirect(reqStr);
			}
		}
		
		arg2.doFilter(arg0, arg1);
		
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
